package com.handpay.zztong.hp;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.bluetooth.BluetoothDevice;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.TextUtils;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpSFTConnector;
import com.handpay.framework.notice.ApiNoticeFactory;
import com.handpay.framework.notice.ApiNoticeListener;
import com.handpay.framework.utils.ActivityStack;
import com.handpay.framework.utils.MyAsyncTask;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.config.UMengKey;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.db.ormlite.DataBaseComponentModel;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.log.PlainLogger;
import com.handpay.zztong.hp.log.Storage;
import com.handpay.zztong.hp.log.StorageUtility;
import com.handpay.zztong.hp.main.activity.MainActivity;
import com.handpay.zztong.hp.main.model.component.ComponentItemBean;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.swiper.SwiperUtils;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.utils.UmengGetTestDevices;
import com.umeng.analytics.MobclickAgent;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

public class ZZTApplication extends Application {

    public static ZZTApplication ZZTApp = null;
    private String TAG = "ZZTApplication";

    // 授权Key
    // 申请地址：http://developer.baidu.com/map/android-mobile-apply-key.htm--FDE126CE41065C93CF5B35D67DBF00D0B4A8CC33
    public String mStrKey = "DB215B40255A4F130B2E1E737556CF555AEDE823";
    boolean m_bKeyRight = true; // 授权Key正确，验证通过
    private LocationClient mLocationClient;

    //    private HashMap<String, Boolean> mapActivity = new HashMap<String, Boolean>();// 用于存储activity对应的激活状态
    public BluetoothDevice bdDevice;

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onCreate() {
        String logFilePath = StorageUtility.combinePath(getApplicationInfo().dataDir, "plainlog.txt");
        HPLog.SetLogger(PlainLogger.instance(logFilePath));
        Storage.initialize(getApplicationContext(), "zzTong");
        MobclickAgent.setDebugMode(false);
        //获取设备号用于友盟添加测试设备
        HPLog.i("umeng", UmengGetTestDevices.getDeviceInfo(this));
        JPushInterface.setDebugMode(false);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush
        registerLocation();
        super.onCreate();
        ZZTApp = this;
        HttpSFTConnector.init(this);//init http utils
        PackageManager manager = this.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            ClientEngine.VERSION = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }

        ActivityLifecycleCallbacks callbacks = new ActivityLifecycleCallbacks() {
            private int numRunningActivities = 0;

            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
                numRunningActivities++;
                if (numRunningActivities == 1) {
                    HPLog.i(TAG, "APP IN FOREGROUND");
                    ApiNoticeFactory.getInstance().doBroadCastNotice(ApiNoticeListener.CUSTOM_COMPONENT_ACTION, null);
                    ApiNoticeFactory.getInstance().doBroadCastNotice(ApiNoticeListener.VERIFY_UPDATE_ACTION, null);
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
                numRunningActivities--;
                if (numRunningActivities == 0) {
                    HPLog.i(TAG, "APP IN BACKGROUND");
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        };
        this.registerActivityLifecycleCallbacks(callbacks);
        //7.0以后
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
    }

//    private void test() {
//        RequestQueue requestQueue;
//        if (ZZTConfig.isUseHTTPS) {
//            //双向认证
//            InputStream p12Keystore = getResources().openRawResource(R.raw.safepayclient);
//            InputStream trustKeyStore = getResources().openRawResource(R.raw.safepayserver);
//            requestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack(null, SSLCustomSocketFactory.getSocketFactory(p12Keystore, "1234567890", trustKeyStore)));
//            //单项认证
////            InputStream trustKeyStore = getResources().openRawResource(R.raw.handpayssl);
////            requestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack(null, SSLCustomSocketFactory.getSocketFactory(trustKeyStore, "handpay")));
//
//        } else {
//            requestQueue = Volley.newRequestQueue(getApplicationContext());
//        }
//        Hashtable<String, String> params = new Hashtable<String, String>();
//        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
//        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
//        HttpSFTConnector.doVolleyJsonPost(new NetEngineListener() {
//            @Override
//            public void callbackNetResponse(String action, Hashtable<String, Object> resp, boolean showAlert, boolean dataCompile) {
//            }
//
//            @Override
//            public void callbackJsonNetResponse(String action, ResponseBean resp, boolean showAlert) {
//                String a = "";
//            }
//        }, requestQueue, ZZTongActivity.Do_CustomComponentList, ResponseBean.class, params, false, 0);
//    }

    private void registerLocation() {
        mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
        mLocationClient.registerLocationListener(new MyLocationListener()); // 注册监听函数
        //设置定位SDK的定位方式
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
        option.setIsNeedAddress(true);// 返回的定位结果包含地址信息
        option.setOpenGps(true);//默认false,设置是否使用gps
//        option.setIsNeedLocationDescribe(true);//设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
//        option.setIgnoreKillProcess(false);//退出应用是否停止定位
        if (ZZTConfig.ENV.PRINTLOG) {
            // option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);
        }
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    public void requestLocation() {
        if (mLocationClient != null && mLocationClient.isStarted())
            mLocationClient.requestLocation();
        else {
            HPLog.e("LocSDK7", "locClient is null or not started");
        }
    }

    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) return;
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            if (location.getLocType() == 167) {
                //请打开权限
            }
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());//定位精度  单位米
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation) {
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\naddr : ");
                sb.append(location.getAddrStr()); //获取地址信息
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\noperationers : ");
                sb.append(location.getOperators());    //获取运营商信息
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());    //位置语义化信息

            double latitude = location.getLatitude();
            double longitude = location.getLongitude();

            HPLog.i(HPLog.TAG_RESULT, "Location:" + sb.toString());

            StringBuilder sbaddress = new StringBuilder(100);
            if (!TextUtils.isEmpty(location.getProvince())) {
                sbaddress.append(location.getProvince());
            }
            if (!TextUtils.isEmpty(location.getCity())) {
                sbaddress.append('|');
                sbaddress.append(location.getCity());
            }
            if (!TextUtils.isEmpty(location.getDistrict())) {
                sbaddress.append('|');
                sbaddress.append(location.getDistrict());
            }
            if (!TextUtils.isEmpty(location.getStreet())) {
                sbaddress.append('|');
                sbaddress.append(location.getStreet());
            }
            if (!TextUtils.isEmpty(location.getStreetNumber())) {
                sbaddress.append('|');
                sbaddress.append(location.getStreetNumber());
            }
            HPLog.i(HPLog.TAG_RESULT, "address:" + sbaddress.toString());
            if (!TextUtils.isEmpty(sbaddress.toString())) {
                HPLog.e(HPLog.TAG_RESULT, "address latitude:" + latitude + "|longitude:" + longitude);
                ClientEngine.getInstance().saveGlobal(BaseProtocolKey.KEY_LATITUDE, latitude);
                ClientEngine.getInstance().saveGlobal(BaseProtocolKey.KEY_LONGTITUDE, longitude);
                ClientEngine.getInstance().saveGlobal(BaseProtocolKey.KEY_ADDRESS, sbaddress.toString());
            } else {
                // 如果address目前没有。去做geo
                if (ZZTConfig.ENV.PRINTLOG) {
                    // geoRevert(latitude, longitude);
                }
            }
        }

        //移动热点判别 SDK v7.1新增,调用该方法：LocationClient.requestHotSpotState()
        @Override
        public void onConnectHotSpotMessage(String connectWifiMac, int hotSpotState) {
            //LocationClient.CONNECT_HPT_SPOT_TRUE - 连接的是移动热点
            //LocationClient.CONNECT_HPT_SPOT_FALSE - 连接的非移动热点
            //LocationClient.CONNECT_HPT_SPOT_UNKNOWN - 连接状态未知
        }
    }

    volatile boolean mGeoReverting = false;

    public void geoRevert(final double lat, final double lon) {
        if (mGeoReverting) {
            return;
        }
        mGeoReverting = true;
        HPLog.i("geoRevert", "reverting");
        new MyAsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                // String template =
                // "http://api.map.baidu.com/geocoder/v2/?ak=lMPRPG1YFdMBnRqqP9gmRlP8&location=%f,%f&output=json&pois=0";
                String template = "http://api.map.baidu.com/geocoder?location=%f,%f&output=json&key=7ED6576827E61B34742E834C5CEBFA1BC46E2495";
//				String url = String.format(template, lat, lon);
                String url = String.format(template, 115.553322d, 40.34272d);
                HttpGet httpGet = new HttpGet(url);
                try {
                    HttpResponse response = new DefaultHttpClient().execute(httpGet);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        String result = EntityUtils.toString(response.getEntity());
                        JSONObject resultObj = new JSONObject(result);
                        if ("OK".equals(resultObj.getString("status"))) {
                            JSONObject address = resultObj.getJSONObject("result").getJSONObject("addressComponent");
                            String province = address.getString("province");
                            String city = address.getString("city");
                            String district = address.getString("district");
                            String street = address.getString("street");
                            String street_number = address.getString("street_number");
                            StringBuilder sbaddress = new StringBuilder(100);
                            if (!TextUtils.isEmpty(province)) {
                                sbaddress.append(province);
                            }
                            if (!TextUtils.isEmpty(city)) {
                                sbaddress.append('|');
                                sbaddress.append(city);
                            }
                            if (!TextUtils.isEmpty(district)) {
                                sbaddress.append('|');
                                sbaddress.append(district);
                            }
                            if (!TextUtils.isEmpty(street)) {
                                sbaddress.append('|');
                                sbaddress.append(street);
                            }
                            if (!TextUtils.isEmpty(street_number)) {
                                sbaddress.append('|');
                                sbaddress.append(street_number);
                            }
                            if (!TextUtils.isEmpty(sbaddress.toString())) {
                                HPLog.e("geoRevert", "addresss: " + sbaddress.toString());
                                ClientEngine.getInstance().saveGlobal(BaseProtocolKey.KEY_LATITUDE, lat);
                                ClientEngine.getInstance().saveGlobal(BaseProtocolKey.KEY_LONGTITUDE, lon);
                                ClientEngine.getInstance().saveGlobal(BaseProtocolKey.KEY_ADDRESS, sbaddress.toString());
                            }
                        } else {
                            HPLog.e("geoRevert", "status: " + resultObj.getInt("status"));
                        }
                    } else {
                        HPLog.e("geoRevert", "status: " + response.getStatusLine().getStatusCode());
                    }
                } catch (IOException ioe) {
                    HPLog.e("geoRevert", "", ioe);
                } catch (JSONException jsonE) {
                    HPLog.e("geoRevert", "", jsonE);
                } catch (NullPointerException nE) {
                    HPLog.e("geoRevert", "", nE);
                }
                HPLog.i("geoRevert", "end");
                mGeoReverting = false;
                return null;
            }
        }.execute();
    }

    public static ZZTApplication getApp() {
        return ZZTApp;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        exitApp();
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        exitApp();
    }

    /**
     * 退出app业务态，释放资源（注：结束进程只做辅助用）
     */
    public synchronized void exitApp() {
        ActivityStack.getInstance().finishAll();
        killSelf();
    }

    public void umengEvent(String eventId, HashMap<String, String> map) {
        if (TextUtils.isEmpty(eventId)) {
            return;
        }
        if (null == map) {
            map = new HashMap<String, String>(4);
            map.put(UMengKey.HashMapKey.DES, eventId);
        }
        map.put(UMengKey.HashMapKey.TRADE_CHANNEL, ZZTConfig.CHANNEL);
        map.put(UMengKey.HashMapKey.CSN, SwiperUtils.getCsn());
        map.put(UMengKey.HashMapKey.TUDID, ClientEngine.getInstance().getDeviceUuid());
        MobclickAgent.onEvent(this, eventId, map);
    }

    private void killSelf() {
        // 退出应用前，调用umeng回调
//        MobclickAgent.onKillProcess(this);
        // 退出，由于android不建议直接结束进程，故此处只做辅助用
        // ActivityManager am = (ActivityManager)
        // getSystemService(ACTIVITY_SERVICE);
        // am.killBackgroundProcesses(getPackageName());
        // am.forceStopPackage(getPackageName());
//         android.os.Process.killProcess(android.os.Process.myPid());
        // System.exit(0);
    }

//    /**
//     * 把Activity和状态放到List中管理
//     *
//     * @param activity
//     * @param isAlive
//     */
//    public void addActivityStatus(Activity activity, boolean isAlive) {
//
//        if (mapActivity.containsKey(activity.getClass().getName())) {
//            mapActivity.remove(activity.getClass().getName());
//            mapActivity.put(activity.getClass().getName(), isAlive);
//        } else {
//            mapActivity.put(activity.getClass().getName(), isAlive);
//        }
//
//    }

//    /**
//     * 判断是否有Activity是活动状态
//     *
//     * @return
//     */
//    public boolean isAllActivityAlive() {
//        boolean res = false;
//        Iterator iter = mapActivity.entrySet().iterator();
//        while (iter.hasNext()) {
//            Map.Entry entry = (Map.Entry) iter.next();
//            Object key = entry.getKey();
//            boolean value = (Boolean) entry.getValue();
//            if (value) {
//                return true;
//            }
//        }
//
//        return res;
//    }

    public static ZZTApplication getInstance() {
        return ZZTApp;
    }

    public MainActivity mainActivity;

    public MainActivity getMainActivity() {
        return mainActivity;
    }

    public void setMainActivity(MainActivity activity) {
        this.mainActivity = activity;
    }

    AccountUtils.Account mAccount;

    public void setAccount(AccountUtils.Account account) {
        this.mAccount = account;
    }

    public AccountUtils.Account getAccount() {
        return mAccount;
    }

}
